import { EventBus } from '@/utils/'
import { COMPONENT_TYPES } from '@/const/'
import { env } from '@/main'

let isLoadJsObj: any = {}
let loadJsLen = 0
let loadedJsLen = 0
const resetLoadJsObj = () => {
  isLoadJsObj = {}
}
const addLoadJsLib = (componentData: IComponent) => {
  const cid = componentData.cid
  if(cid == COMPONENT_TYPES.group_carousel) {
    isLoadJsObj.isSwiper = true
  } else if (cid == COMPONENT_TYPES.wb_imgs) {
    isLoadJsObj.isSwiper = true
  } else if (cid == COMPONENT_TYPES.wb_scroll_container) {
    isLoadJsObj.isSwiper = true
  } else if (cid == COMPONENT_TYPES.wb_video) {
    isLoadJsObj.isVideo = true
  } else if (cid == COMPONENT_TYPES.wb_audio) {
    isLoadJsObj.isAudio = true
  }
} 

const loadJsLib = () => {
  loadJsLen = 0
  loadedJsLen = 0
  const webUrl = env.baseUrl
  const scripts: any[] = []
  const links: any[] = []
  if(!window.Swiper && isLoadJsObj.isSwiper) {
    links.push({ rel: 'stylesheet', href: webUrl + 'css/swiper-bundle.min.css?v=7' })
    scripts.push({ src: webUrl + 'js/swiper-bundle.min.js?v=7', type: 'text/javascript', charset: 'utf-8' })
  }
  if(!window.videojs && isLoadJsObj.isVideo) {
    scripts.push({ src: webUrl + 'js/video.min.js', type: 'text/javascript', charset: 'utf-8'})
    links.push({ rel: 'stylesheet', href: webUrl + 'css/video-js.css' })
  }
  if(!window.APlayer && isLoadJsObj.isAudio) {
    scripts.push({ src: webUrl + 'js/APlayer.min.js?v=1', type: 'text/javascript', charset: 'utf-8'})
  }
  loadJsLen = scripts.length
  _.forEach(scripts, (script: any) => {
    loadCssOrScript(script.src, loadCompleteCallback)
  })
  _.forEach(links, (link: any) => {
    loadCssOrScript(link.href)
  })
}

const loadHtml2Canvas = (cb: Function) => {
  const webUrl = env.baseUrl
  const script = { src: webUrl + 'js/html2canvas.min.js?v=1', type: 'text/javascript', charset: 'utf-8' }
  loadCssOrScript(script.src, cb)
}

const loadCompleteCallback = () => {
  EventBus.$emit('loadJsComplete')
}

const loadCssOrScript = (url: string, fn?: Function) => {
  loadedJsLen++
  let Head = document.getElementsByTagName('head')[0]
  let linkScript: any
  /* eslint-disable */
  if(/\.css[^\.]*$/.test(url)) {
    linkScript = document.createElement("link")
    linkScript.type = "text/" + ("css")
    linkScript.rel = "stylesheet"
    linkScript.href = url
  } else {
    linkScript = document.createElement("script")
    linkScript.type = "text/" + ("javascript")
    linkScript.src = url
  }
  Head.insertBefore(linkScript, Head.lastChild)
  linkScript.onload = linkScript.onerror = () => {
    if(fn && loadedJsLen >= loadJsLen) fn()
  }
}

export {
  resetLoadJsObj,
  addLoadJsLib,
  loadJsLib,
  loadHtml2Canvas
}